<template>
  <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px"
   v-loading="loading">
    <el-form-item :label="$t('table.username')" prop="username">
      <el-input v-model="temp.username" />
    </el-form-item>
    <el-form-item :label="$t('table.newPassword')" prop="newPassword">
      <el-input v-model="temp.newPassword" />
    </el-form-item>
    <el-form-item :label="$t('table.verifyPassword')" prop="verifyPassword">
      <el-input v-model="temp.verifyPassword" />
    </el-form-item>
    <el-button type="primary" @click="handleUpdate">
      {{ $t('table.confirm') }}
    </el-button>
  </el-form>
</template>

<script>
import { updateMyInfo } from '@/api/user'
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          username: '',
          email: ''
        }
      }
    }
  },
  data(){
    return {
      temp: {
        username: '',
        password: '',
        verifyPassword: '',
      },
      rules: {
        username: [{ required: true, message: 'username is required', trigger: 'blur' }],
        verifyPassword: [{ required: true, message: 'verifyPassword is required', trigger: 'blur' }],
      },
      loading: false
    }
  },
  created(){
    this.resetTemp()
  },
  methods: {
    resetTemp(){
      this.temp = {
        username: this.user.username,
        password: '',
        verifyPassword: '',
      }
    },
    submit() {
      this.$message({
        message: 'User information has been updated successfully',
        type: 'success',
        duration: 5 * 1000
      })
    },
    handleUpdate(){
      this.$refs.dataForm.validate().then(valid => {
        if(valid){
          this.loading = true
          updateMyInfo(this.temp).then(async res => {
            console.log(res, 'res')
            this.loading = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            await this.$store.dispatch('user/logout')
          this.$router.push(`/login?redirect=${this.$route.fullPath}`)
          }).catch(err => {
            console.log(err, 'updateUser')
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
